<html>
<head><title>CS 143 Project 1A</title></head>
<body>

<h1>CALCULATOR</h1>
CS 143 Project 1A Solution<br />
Author: Ervin Sukardi  (SID 203 808 277)<br />
Ver 1.0    April 10, 2012<br />
<br />

Issues:<br />
<ul>
</ul>

Insert your equation:<br />
<form method="GET">
<input type="text" name="problem" />
<input type="submit" />
</form>

Result:<br />
<?php
if($_GET["problem"])
{
    $equ = $_GET["problem"];
    $pattern = "#^\-?[0-9]+(\.[0-9]*)?([ ]*[+\-\*/][ ]*\-?[0-9]+(\.[0-9]*)?)*[ ]*$#";

    // Use preg_match to check if expression is valid. For it to be valid,
    //  - the entire string must fit an equation structure
    //  - the equation have only valid characters (+-*/, 0-9, ., and spaces)
    //  - there cannot be any --
    //  - there must be no zero term following a division sign
    if(	preg_match($pattern, $equ) == 1 &&
       	preg_match("#[^ \t0-9+\-*/\.]#", $equ) == 0 &&
    	preg_match("#\-\-#", $equ) == 0 &&
    	preg_match("#/[ ]*0+($|[^0-9\.])+|/[ ]*0+\.0+($|[^0-9])+#", $equ) == 0 )
    {
	    // If valid, evaluate expression
		eval("\$ans = $equ;");
		echo $equ." = ".$ans."<br />";
    }
    else
    {
    	// If invalid, gracefully display an error
    	echo "\"".$equ."\" is an invalid expression<br />";
    }
}
?>

</body>
</html>
